<template>
  <el-dialog
    :title="$t(uploadTitle)"
    width="1000px"
    center
    :visible.sync="showUpload"
  >
    <el-progress v-if="showProgress" :percentage="progress"></el-progress>
    <div v-if="isIframe && fileType === 'video'" class="top-video-switch">
      <el-tabs class="lb-tabs" v-model="activeName">
        <el-tab-pane label="本地视频" name="1">
          <div v-loading="loading" class="img-view">
            <div
              class="img-item"
              v-for="(item, index) in fileList"
              :key="index"
              :style="{
                'background-image': `url(${
                  lbFileType === 'image' ? item.url : defaultBGImg
                })`
              }"
              @click="choiceImg(index)"
            >
              <div class="img-name">{{ item.filename }}</div>
              <i v-show="item.checked" class="icon-selected el-icon-check"></i>
              <i
                class="icon-d el-icon-delete-solid"
                @click.stop="confirmDel('single', item.id)"
              ></i>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="提取网络视频" name="2">
          <div class="get-network-video">
            <lb-image
              src="https://lbqny.migugu.com/admin/public/iframe_video.jpeg"
            />
            <el-input
              v-model="networkVideo"
              placeholder="请填写通用代码"
            ></el-input>
            <lb-button type="primary" @click="getNetWorkVideo">提 取</lb-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div v-else v-loading="loading" class="img-view">
      <div
        class="img-item"
        v-for="(item, index) in fileList"
        :key="index"
        :style="{
          'background-image': `url(${
            lbFileType === 'image' ? item.url : defaultBGImg
          })`
        }"
        @click="choiceImg(index)"
      >
        <div class="img-name">{{ item.filename }}</div>
        <i v-show="item.checked" class="icon-selected el-icon-check"></i>
        <i
          class="icon-d el-icon-delete-solid"
          @click.stop="confirmDel('single', item.id)"
        ></i>
      </div>
    </div>
    <div class="upload-page">
      <div class="operate">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          >{{ $t('action.checkAll') }}</el-checkbox
        >
        <el-divider direction="vertical"></el-divider>
        <div>
          <span>{{ $t('action.selected') }}</span>
          <span class="count">{{ selectedFiles.length }}</span>
        </div>
        <lb-button size="mini" type="primary" @click="selectedImgs">{{
          $t('action.comfirm')
        }}</lb-button>
        <lb-button size="mini" type="danger" @click="confirmDel('more')">{{
          $t('action.delete')
        }}</lb-button>
        <el-divider direction="vertical"></el-divider>
        <lb-button
          size="mini"
          type="primary"
          @click="$refs['inputImg'].click()"
          >{{ $t('action.upload') }}</lb-button
        >
        <input
          type="file"
          :accept="acceptType"
          :multiple="lbFileType === 'image'"
          style="display: none"
          @change="uploadFiles"
          ref="inputImg"
        />
      </div>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="page"
        :page-size="limit"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visibles: {
      type: Boolean,
      default: false
    },
    fileType: {
      type: String,
      default: 'image'
    },
    isIframe: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      activeName: '1',
      networkVideo: '',
      loading: false,
      page: 1,
      limit: 10,
      total: 0,
      showUpload: false,
      isIndeterminate: false,
      checkAll: false,
      defaultBGImg: '', // 不是图片类型时的列表默认背景图
      fileList: [], // 图片、视频、音频列表数据
      uploadTitle: '', // 上传的标题
      lbFileType: 'image', // 文件类型
      acceptType: 'image/*', // 上传的文件类型
      progress: 0,
      showProgress: false
    }
  },
  created () {
    this.handleFileType(this.fileType)
  },
  methods: {
    /**
       * @method 根据fileType处理不同的文件类型
       */
    handleFileType (type) {
      this.lbFileType = type
      this.uploadTitle = `title.${type}Upload`
      this.acceptType = `${type}/*`
      if (type !== 'image') this.defaultBGImg = require(`@/assets/${type}.png`)
      if (this.showUpload) this.getFileList()
    },

    /**
       * @method 获取图片、音频、视频
       */
    getFileList () {
      this.loading = true
      let {
        page,
        limit,
        lbFileType
      } = this
      let type = lbFileType === 'image' ? 1 : lbFileType === 'audio' ? 2 : lbFileType === 'video' ? 3 : 4
      this.$api.getUploadFiles({
        type,
        page,
        limit
      }).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.fileList = res.data.files.map(item => {
            item.checked = false
            item.url = item.longbing_attachment_path || item.attachment
            return item
          })
          this.total = res.data.total
        }
      })
    },

    /**
       * @method 切换分页
       */
    handleCurrentChange (val) {
      this.page = val
      this.getFileList()
    },

    /**
       * @method 全选
       */
    handleCheckAllChange () {
      let {
        checkAll
      } = this
      this.fileList.forEach(item => {
        item.checked = checkAll
      })
    },

    /**
       * @method 选中的图片、视频、音频
       */
    choiceImg (index) {
      this.fileList[index].checked = !this.fileList[index].checked
      let {
        fileList
      } = this
      let arr = fileList.filter(item => {
        return item.checked
      })
      this.isIndeterminate = arr.length > 0 && arr.length < fileList.length
      this.checkAll = arr.length === fileList.length
    },

    /**
       * @method 删除确认框
       */
    confirmDel (type, fid) {
      if (type === 'more' && this.selectedFiles.length === 0) return false
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        let ids = []
        if (type === 'more') {
          ids = this.selectedFiles.map(item => {
            return item.id
          })
        } else ids = [fid]
        this.$api.delFiles({
          ids
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: this.$t('tips.successDel')
            })
            this.getFileList()
          }
        })
      })
    },

    /**
       * @method 上传图片，视频，音频
       */
    uploadFiles (e) {
      let {
        lbFileType
      } = this
      let files = e.target.files
      if (files.length === 0) return false
      let formData = new FormData()
      console.log(formData, '====formData1111111')

      for (let i = 0, len = files.length; i < len; i++) {
        formData.append('file[]', files[i])
      }
      formData.append('type', lbFileType === 'image' ? 'picture' : lbFileType)
      this.progress = 0
      this.showProgress = true
      this.$api.uploadFiles(formData, this.getProgress).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t('tips.successUpload'))
          this.getFileList()
        }
      })
    },

    /**
       * @method 提取网络视频
       */
    getNetWorkVideo () {
      let {
        networkVideo
      } = this
      let _html = ''
      if (networkVideo.indexOf('<iframe') >= 0) {
        let htmlArr = networkVideo.split('src')
        _html = htmlArr[0] + ` wdith='300' height='200' src` + htmlArr[1]
      } else {
        _html =
          `<iframe frameborder="0" src="${networkVideo}" wdith='300' height='200' allowFullScreen="true"></iframe>`
      }
      this.$emit('selectedFiles', [{
        type: 5,
        url: _html
      }])
      this.showUpload = false
    },

    /**
       * @method 获取上传的进度
       */
    getProgress (e) {
      this.progress = e.loaded / e.total * 100 | 0
      if (this.progress >= 100) {
        setTimeout(() => {
          this.showProgress = false
        }, 500)
      }
    },

    /**
       * @method 点击确定选中的图片
       */
    selectedImgs () {
      let {
        fileList
      } = this
      let checkedImgs = fileList.filter(item => {
        return item.checked
      })
      this.fileList.forEach(item => {
        item.checked = false
      })
      this.$emit('selectedFiles', checkedImgs)
      this.showUpload = false
    }
  },
  watch: {
    showUpload (val) {
      if (!val) {
        this.fileList = []
        this.page = 1
        this.total = 0
      }
      this.$emit('update:visibles', val)
    },
    visibles (val) {
      this.handleFileType(this.fileType)
      this.showUpload = val
      if (val) {
        this.getFileList()
      }
    },
    fileList: {
      deep: true,
      handler (val) {
        let checkedArr = val.filter(item => {
          return item.checked
        })
        this.checkAll = checkedArr.length === val.length && val.length !== 0
        this.isIndeterminate = checkedArr.length > 0 && checkedArr.length < val.length
      }
    }
  },
  computed: {
    selectedFiles () {
      return this.fileList.filter(item => {
        return item.checked
      })
    }
  },
  filters: {
    filterCheked (arr) {
      let a = arr.filter(item => {
        return item.checked
      })
      return a.length
    }
  },
  beforeDestroy () {
    // this.$store.commit('handleUploadStatus', false)
  }
}
</script>

<style lang="scss" scoped>
.img-view {
  width: 100%;
  height: 398px;
  padding: 20px 0;
  border-top: 1px solid $lineColor;
  border-bottom: 1px solid $lineColor;
  display: flex;
  flex-wrap: wrap;
  position: relative;

  .loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, 50%);
  }

  .img-item {
    width: 16%;
    height: 140px;
    background-color: $columnBgColor;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center center;
    margin: 2%;
    position: relative;
    border: 2px solid $columnBgColor;
    cursor: pointer;

    .img-name {
      width: 100%;
      height: 32px;
      position: absolute;
      bottom: 0px;
      right: 0;
      left: 0;
      margin: auto;
      background: rgba($color: #000000, $alpha: 0.5);
      z-index: 10;
      line-height: 32px;
      color: #fff;
      padding: 0 20px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .icon-selected {
      display: inline-block;
      width: 100%;
      height: 100%;
      background: rgba($color: #000000, $alpha: 0.5);
      position: absolute;
      top: 0;
      left: 0;
      z-index: 15;
      color: #fff;
      font-size: 60px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .icon-d {
      display: none;
      width: 32px;
      height: 32px;
      background: #4c88d8;
      color: #fff;
      text-align: center;
      line-height: 32px;
      position: absolute;
      right: 0;
      bottom: 0;
      z-index: 20;
      font-size: 20px;
    }

    &:hover {
      border: 2px solid #4c88d8;
      width: 16%;

      .icon-d {
        display: inline-block;
      }
    }
  }
}

.lb-tabs .img-view {
  border-top: none;
}

.top-video-switch {
  width: 100%;
  border-bottom: 1px solid $lineColor;
}

.get-network-video {
  height: 398px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;

  .el-input {
    width: 500px;
  }
}

.upload-page {
  margin-top: 20px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .operate {
    display: flex;
    align-items: center;

    .el-checkbox {
      margin-right: 10px;
    }

    .count {
      color: #4c88d8;
      margin-left: 5px;
      margin-right: 10px;
    }

    .el-button {
      margin-left: 10px;
    }
  }
}
</style>
